﻿// Extensions Made Easy - Copyright 2012 by Jan Van der Haegen - All rights reserved, use for educational purposes only.

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using Microsoft.LightSwitch.Runtime.Shell;
using Microsoft.VisualStudio.ExtensibilityHosting;

namespace ExtensionsMadeEasy.ClientAPI.Shell
{
    [InheritedExport(typeof(IShellExporter))] 
    public abstract class EasyShellExporter<T> : IShellExporter
        where T : IShell, new()
    {
        private T shell;

        public IShell GetShell()
        {
            if (!(typeof(T).Assembly.Equals(this.GetType().Assembly)))
            { //Fixes a bug: see "LightSwitch and the MEF story"
                AggregateCatalog catalog = new AggregateCatalog();
                catalog.Catalogs.Add(new AssemblyCatalog(typeof(T).Assembly));
                CompositionContainer container = new CompositionContainer(catalog);
                VsCompositionContainer.Create(container);
            }
            return this.shell == null ? (this.shell = new T()) : this.shell;
        }
    }
}